package com.offcn.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sun.plugin.liveconnect.SecurityContextHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TokenDecode {

    private static final String PUBLIC_KEY = "public.key";

    private static String publicKey = "";

    /**
     * \
     * 获取公钥
     */
    public String getPubkey() {
        if (!StringUtils.isEmpty(publicKey)) {
            return publicKey;
        }
        ClassPathResource resource = new ClassPathResource(PUBLIC_KEY);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            publicKey = bufferedReader.lines().collect(Collectors.joining("\n"));
            return publicKey;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解析令牌数据
     */
    public Map<String, String> getinfo() {
        //获取授权信息
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();

        return decoeToken(details.getTokenValue());
    }

    //获取令牌内容
    private Map<String, String> decoeToken(String tokenValue) {

        Jwt jwt = JwtHelper.decodeAndVerify(tokenValue, new RsaVerifier(getPubkey()));
        String claims = jwt.getClaims();
        return JSON.parseObject(claims, Map.class);
    }
}
